package ae.pcfc.cldos.online.common.clddb.revision.listener;

import org.hibernate.envers.RevisionListener;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import ae.pcfc.cldos.online.common.clddb.domain.CustomRevisionEntity;

/**
 * 
 * @author arosa
 *
 */
public class CustomRevisionListener implements RevisionListener {

	private static final String __USERNAME_NO_CONTEXT = "NO CONTEXT";
	private static final String __USERNAME_NO_AUTHENTIFICATION = "NO AUTH";
	private static final String __USERNAME_NO_USERNAME = "NO USERNAME";
	
	public void newRevision(Object revisionEntity) {
		CustomRevisionEntity cre = (CustomRevisionEntity)revisionEntity;
		SecurityContext sc = SecurityContextHolder.getContext();
		String userName = null;
		if(sc==null){
			userName = __USERNAME_NO_CONTEXT;
		} else {
			Authentication authentication = sc.getAuthentication();
			if(authentication==null){
				userName = __USERNAME_NO_AUTHENTIFICATION;
			}else {
				userName = authentication.getName();
				if(userName==null){
					userName = __USERNAME_NO_USERNAME;
				}
			}
		}
		cre.setUsername(userName);
	}

}
